package thread;

public class TestIpc {
    public static void main(String[] args) {
        SynChink synChink=new SynChink();
        new Product(synChink).start();
        new Costomer(synChink).start();
    }

}
class Chick{
    int id;

    public Chick(int id) {
        this.id = id;
    }
}
class Product extends Thread{
    private SynChink synChink;

    public Product(SynChink synChink) {
        this.synChink = synChink;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            synChink.push(new Chick(i));
            System.out.println("生产了"+i+"只鸡");
        }
    }
}
class Costomer extends Thread{
    private SynChink synChink;

    public Costomer(SynChink synChink) {
        this.synChink = synChink;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了"+synChink.pop().id+"只鸡");
        }
    }
}
class SynChink{
    private Chick [] c=new Chick[10];
    int count=0;
    public synchronized void push(Chick chick){
        if(count==c.length){
            //停止生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        c[count]=chick;
        count++;
        this.notifyAll();
    }
    public synchronized Chick pop(){
        if (count==0){
            //通知生产者，没有货了
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        count--;
        Chick chick=c[count];
        this.notifyAll();
        return chick;
    }
}
